#coding=utf-8
#LightCam 生成hostlist.json
#init by monitor 20150928

import multiprocessing,subprocess,sys
import socket,os,time,re,traceback,json,binascii
import lc_libs,pymongo,threading

def genjson(this):
	
	hostlist=[]
	hosts={
		"id":10,
		"text":"主机列表",
		"children":[]
		}
	
	try:
		itemid=1000
		for item in this:
			hostname=item['hostname']
			if hostname[0]=='#':
				continue
			ostype=item['ostype']
			iconCls="icon-lc_star16"
			if 'linux' in ostype.lower():
				iconCls="icon-redhat16"
			elif 'aix' in ostype.lower():
				iconCls="icon-aix16"
			elif 'hpux' in ostype.lower():
				iconCls="icon-hpux16"
			elif 'windows' in ostype.lower():
				iconCls="icon-windows16"
			itemid+=10
			itemd={
					"id":itemid,
					"text":hostname,
					"iconCls":iconCls,
					"checked":"false"
					}
			hosts['children'].append(itemd)
			
		hosts['children']=sorted(hosts['children'],key=lambda d:d['text'],reverse=False)
		#print hosts['children']
		hostlist.append(hosts)
		jdata=json.dumps(hostlist)
		
		jfile=open(lchome+"/pyweb/static/json/cmdb/lc_hostlist.json",'w')
		jfile.write(jdata)
		jfile.close()


	except Exception:
		excinfo=traceback.format_exc()
		print excinfo
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()

if __name__ == "__main__":
	
	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()

	agent_hostname=lc_libs.lc_gethostname()
	confname=lchome+'/conf/lc_hostlist.conf'
	MonitorList = []

	for lines in open(confname).readlines():
		line=lines.split('\t')
		dconf={}
		
		dconf['hostname']=line[0]
		dconf['ipaddr']=line[1]
		dconf['area']=line[2]
		dconf['ostype']=line[3]
	
		MonitorList.append(dconf)

	genjson(MonitorList)